import React from "react";
import "./TodoMain.css";
//1. 导入 useSelector 函数
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { asyncReqRemoveTodo, asyncReqCheckTodo } from "../../redux/reducers/todoReducer";

export default function TodoMain() {
  //2. 获得 todo 任务数据
  let todo = useSelector((state) => state.todo);
  let dispatch = useDispatch();

  //声明事件回调
  let checkTodo = (id) => {
    return (e) => {
      //修改某个任务的完成状态
      dispatch(asyncReqCheckTodo({id: id, done: e.target.checked}));
    }
  };

  //声明点击事件回调 删除任务
  let remove = (id) => {
    return () => {
      //删除任务分发
      dispatch(asyncReqRemoveTodo(id));
    }
  }
  
  return (
    <ul className="todo-main">
      {/* 3. 列表渲染 */}
      {todo.map((item) => {
        return (
          <li key={item.id}>
            <label>
              <input type="checkbox" checked={item.done} onChange={checkTodo(item.id)} />
              <span className={item.done ? "done" : ""}>{item.title}</span>
            </label>
            <button onClick={remove(item.id)} className="btn btn-danger">删除</button>
          </li>
        );
      })}
    </ul>
  );
}
